using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using UnityEditor;
using UnityEngine;

/// <summary>
/// 如果不加UnityEditor默认继承的是System.AssetModificationProcessor
/// </summary>
public class CC3ResImporter : UnityEditor.AssetModificationProcessor
{
    /// <summary>
    /// 此方法是监听将要进行“创建”的操作，也就是程序到下一帧才会真正执行“创建”。
    /// </summary>
    /// <param name="assetName"></param>
    public static void OnWillCreateAsset(string assetName)
    {
        if (!CheckIsCC3Res(assetName))
        {
            return;
        }

        string assetPath = assetName.Replace(".meta", ""); //清理.meta后缀
        string extension = Path.GetExtension(assetPath);
        if (string.IsNullOrEmpty(extension) || extension.ToLower() != ".fbx") //滤掉后缀错误或者不是模型的
        {
            return;
        }

        Func<Task> AfterCreateAsset = async () =>
        {
            await Task.Delay(TimeSpan.FromSeconds(1f));

            OnModelImport(assetPath);
        };

        AfterCreateAsset();
    }

    /// <summary>
    /// 暂定一个规则 判断是否是CC3相关资源
    /// </summary>
    private static bool CheckIsCC3Res(string assetName)
    {
        if (!assetName.Contains("CC3"))
        {
            return false;
        }

        return true;
    }

    /// <summary>
    /// 处理CC3模型导入后的手动操作，比如Enable ImportBlendShapes
    /// </summary>
    private static void OnModelImport(string modelPath)
    {
        ModelImporter modelImporter = AssetImporter.GetAtPath(modelPath) as ModelImporter;
        if (modelImporter == null)
        {
            return;
        }

        modelImporter.importBlendShapes = true;

        AssetDatabase.ImportAsset(modelPath, ImportAssetOptions.ForceUpdate);
        AssetDatabase.Refresh();

        Debug.Log("导入了CC3Model：" + modelPath);
    }
}
